import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:situation/data/database/sql_provider.dart';
import 'package:situation/domain/db/system_config_domain.dart';
import 'package:situation/shared/constant/app_constant.dart';
import 'package:situation/shared/shared.dart';
import 'package:situation/shared/util/util_sp.dart';

import 'state.dart';

class ServerUrlFormController extends GetxController {
  final ServerUrlFormState state = ServerUrlFormState();
  TextEditingController nameController = TextEditingController();
  TextEditingController serverUrlController = TextEditingController();
  TextEditingController intercomUrlController = TextEditingController();

  SystemConfigDomain domain = Get.arguments;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    // 赋值
    nameController.text = domain.name;
    serverUrlController.text = domain.serverUrl;
    intercomUrlController.text = domain.intercomUrl;
  }

  void save() async {
    if (nameController.text.isEmpty || serverUrlController.text.isEmpty) {
      SmartDialog.showNotify(msg: '请输入完整信息', notifyType: NotifyType.error);
      return;
    }

    if(!UtilValidate.isDomain(serverUrlController.text)){
      SmartDialog.showNotify(msg: '请输入正确的服务器地址', notifyType: NotifyType.failure);
      return;
    }


    var data = {
      "name": nameController.text,
      "serverUrl": serverUrlController.text,
      "intercomUrl": intercomUrlController.text,
    };

    if (domain.id != null) {
      await SqlProvider.instance.rawUpdate(
        """
        UPDATE ${SystemConfigDomain.tableName}
        SET name = ?, serverUrl = ?, intercomUrl = ?
        WHERE id = ?
      """,
        [
          nameController.text,
          serverUrlController.text,
          intercomUrlController.text,
          domain.id,
        ],
      );
      SmartDialog.showToast('修改成功');
      Get.back(result: true);
      return;
    } else {
      await SqlProvider.instance.insert(SystemConfigDomain.tableName, data);
      SmartDialog.showToast('保存成功');
      Get.back(result: true);
    }
  }
}
